use crate::{
    model::{AppState, Config},
    utils::get_config_file,
};
use log::info;
use std::sync::Mutex;
use tauri::{AppHandle, Manager};

pub async fn init(app: AppHandle) -> Result<(), String> {
    let path = get_config_file(&app).expect("config file not found");
    info!("init config, app_config_dir:{:?}", path);

    let state = app.state::<Mutex<AppState>>();

    let mut state = state.lock().map_err(|e| e.to_string())?;
    if !path.exists() {
        state.configs.flush(path)?;
    } else {
        state.configs = Config::from(path);
    }

    // 获取 splashscreen 和 main 窗口
    let splash_win = app
        .get_webview_window("splashscreen")
        .ok_or("Splashscreen window not found")?;

    let main_win = app
        .get_webview_window("main")
        .ok_or("Main window not found")?;

    // 隐藏 splashscreen 窗口
    splash_win
        .hide()
        .map_err(|e| format!("Failed to hide splashscreen window: {}", e))?;

    // 显示 main 窗口
    main_win
        .show()
        .map_err(|e| format!("Failed to show main window: {}", e))?;

    Ok(())
}
